//
//  CreativeWallpaperMenuViewController.m
//  CreativePersonalityWallpaper
//
//  Created by qqqwww on 2018/7/5.
//  Copyright © 2018年 Nealon Young. All rights reserved.
//

#import "CreativeWallpaperMenuViewController.h"
#import <WebKit/WebKit.h>

static const CGFloat BOTTOMCTROLHEIGHT = 40.0f;

@interface CreativeWallpaperMenuViewController ()<WKNavigationDelegate, WKUIDelegate, UIScrollViewDelegate>

@property (assign, nonatomic) BOOL isNewPlatform;

@property (strong, nonatomic) UIImage *cacheImg;

@property (copy, nonatomic) NSString *fenXiangLJ;

@property (copy, nonatomic) NSString *fenXiangtui;

@property (copy, nonatomic) NSString *fenXiangText;

@property (copy, nonatomic) NSString *userCenterUri;

@property (copy, nonatomic) NSString *imgUri;

@property (copy, nonatomic) NSString *shouyeUrl;

@property (copy, nonatomic) NSString *lianjie;

@property (nonatomic, strong) WKWebView *webView;

@end

@implementation CreativeWallpaperMenuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:51.0/255.0 green:51.0/255.0 blue:51.0/255.0 alpha:1.0];

    [self instanthePushMainViewController];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)instanthePushMainViewController {
    
    NSArray *arr = [self.str componentsSeparatedByString:@","];
    CGFloat btnWidth = Screen_Width/(arr.count - 1);
    
    NSString *butt = arr.lastObject;
    
    NSArray *adsua = [butt componentsSeparatedByString:@"--"];
    
    [self setupLianJie:adsua[0] userCenter:adsua[1]  fenxiangLJ:adsua[2] text:adsua[3] imageUri:adsua[4] shouye:adsua[5]];
    
    for (int i = 0; i < arr.count-1; i++) {
        NXSimpleButton *btn = [NXSimpleButton buttonWithType:UIButtonTypeCustom];
        btn.tag = i;
        NSString *title = arr[i];
        //        btn.backgroundColor = [UIColor colorWithRed:202/255.0 green:8/255.0 blue:22/255.0 alpha:1.000];
        btn.backgroundColor = [UIColor colorWithRed:28.0/255.0 green:106/255.0 blue:71.0/255.0 alpha:1.0];
        btn.layer.borderWidth = 0.5;
        btn.highlightedColor = [UIColor redColor];
        btn.layer.borderColor = [UIColor whiteColor].CGColor;
        [btn setTitle:title forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:15];
        if (IsIphoneX) {
            btn.frame = CGRectMake(btnWidth*i, Screen_Height-BOTTOMCTROLHEIGHT-37, btnWidth, BOTTOMCTROLHEIGHT);
        }
        else{
            btn.frame = CGRectMake(btnWidth*i, Screen_Height-BOTTOMCTROLHEIGHT, btnWidth, BOTTOMCTROLHEIGHT);
        }
        
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
    }
}

-(void)btnClick:(UIButton *)btn {
    
    switch (btn.tag) {
        case 0:
        {
            NSURL *webURL = [NSURL URLWithString:self.shouyeUrl];
            [_webView loadRequest:[NSURLRequest requestWithURL:webURL]];
        }
            break;
        case 1:
        {
            if ([_webView canGoBack]) {
                [_webView goBack];
            }
        }
            break;
        case 2:
        {
            if ([_webView canGoForward]) {
                [_webView goForward];
            }
        }
            break;
        case 3:
        {
            [_webView reload];
        }
            break;
        case 4:
        {
            [self shareBtnClicked];
            //            if (self.isNewPlatform) {
            //                NSURL *adsddd = [NSURL URLWithString:self.fenXiangLJ];
            //                NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:adsddd];
            //                [self.webView loadRequest:request];
            //            }
        }
            break;
        default:
            break;
    }
}

- (void)setupLianJie:(NSString *)lianjie userCenter:(NSString *)userCenter fenxiangLJ:(NSString *)fenxiangLJ text:(NSString *)text imageUri:(NSString *)imgUri shouye:(NSString*)shouye {
    
    self.shouyeUrl = shouye;
    self.lianjie = lianjie;
    self.userCenterUri = userCenter;
    self.fenXiangLJ = fenxiangLJ;
    self.fenXiangText = text;
    self.imgUri = imgUri;
    self.isNewPlatform = self.userCenterUri.length > 5;
    
    NSURL *webURL = [NSURL URLWithString:self.lianjie];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:webURL];
    [self.webView loadRequest:request];
    [self.view addSubview:self.webView];
}

- (WKWebView *)webView {
    
    if (!_webView) {
        
        int y = 20;
        int x = 0;
        if (IsIphoneX) {
            y = 44;
            x = 67;
        }
        CGRect frame = CGRectMake(0, y, Screen_Width, [UIApplication sharedApplication].delegate.window.rootViewController.view.bounds.size.height-y-BOTTOMCTROLHEIGHT-x);
        if (IsIphoneX) {
            frame = CGRectMake(0, y, Screen_Width, [UIApplication sharedApplication].delegate.window.rootViewController.view.bounds.size.height-y-BOTTOMCTROLHEIGHT-37);
        }
        
        
        _webView = [[WKWebView alloc] initWithFrame:frame];
        
        WKWebViewConfiguration*config = [[WKWebViewConfiguration alloc] init];
        config.preferences = [[WKPreferences alloc] init];
        config.preferences.minimumFontSize =10;
        config.preferences.javaScriptEnabled =YES;
        config.preferences.javaScriptCanOpenWindowsAutomatically =NO;
        NSMutableString *javascript = [NSMutableString string];
        //禁止长按
        [javascript appendString:@"document.documentElement.style.webkitTouchCallout='none';"];
        //禁止选择
        [javascript appendString:@"document.documentElement.style.webkitUserSelect='none';"];
        WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        _webView = [[WKWebView alloc] initWithFrame:frame configuration:config];
        [_webView.configuration.userContentController addUserScript:noneSelectScript];
        
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        _webView.scrollView.delegate = self;
        [_webView setMultipleTouchEnabled:YES];
        [_webView setAutoresizesSubviews:YES];
        [_webView.scrollView setAlwaysBounceVertical:YES];
        [_webView setAllowsBackForwardNavigationGestures:true];
        [_webView sizeToFit];
        
        self.extendedLayoutIncludesOpaqueBars = YES;
        if (@available(iOS 11.0, *)) {
            _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        
    }
    return _webView;
}

- (void)shareBtnClicked {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *textToShare = self.fenXiangText;
        NSString *shareLink = nil;
        
        shareLink  = self.fenXiangLJ;
        
        if (!self.cacheImg && self.imgUri.length>5) {
            NSError *er = nil;
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.imgUri] options:NSDataReadingMappedIfSafe error:&er];
            if (!er) {
                self.cacheImg = [UIImage imageWithData:data];
            }
        }
        NSURL *urlToShare = [NSURL URLWithString:shareLink];
        NSArray *activityItems = @[textToShare,urlToShare];
        if (self.cacheImg) {
            activityItems = @[textToShare,urlToShare,self.cacheImg];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
            if([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
                UIActivityViewControllerCompletionWithItemsHandler myBlock = ^(NSString *activityType,BOOL completed,NSArray *returnedItems,NSError *activityError) {};
                activityVC.completionWithItemsHandler = myBlock;
            }
            activityVC.excludedActivityTypes = @[
                                                 UIActivityTypeMail,
                                                 UIActivityTypePostToFlickr,
                                                 UIActivityTypePostToVimeo,
                                                 ];
            [self presentViewController:activityVC animated:YES completion:nil];
        });
    });
    
}

#pragma mark - < WKWebViewDelegate >
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    WKFrameInfo *frameInfo = navigationAction.targetFrame;
    if (![frameInfo isMainFrame]) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}


- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    
    if (message.length > 6) {
        NSString *scheme = [message substringToIndex:5];
        if ([scheme isEqualToString:@"share"]) {
            NSArray *adsd = [message componentsSeparatedByString:@"share:"];
            self.fenXiangtui = adsd.lastObject;
            [self shareBtnClicked];
            
            completionHandler();
            return;
        }
    }
    
    [self showAlterViewControllerWithMessage:message];
    completionHandler();
}


- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    [SVProgressHUD showWithStatus:@"正在加载中..."];
    NSString *url = navigationAction.request.URL.absoluteString;
    if (url.length > 5) {
        if ([[url substringWithRange:NSMakeRange(url.length-4, 4)] isEqualToString:@".apk"]) {
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
    if (![navigationAction.request.URL.scheme isEqualToString:@"https"] &&
        ![navigationAction.request.URL.scheme isEqualToString:@"http"]) {
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}


- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    [SVProgressHUD dismiss];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    [SVProgressHUD dismiss];
}

#pragma mark - < Alter >
- (void)showAlterViewControllerWithMessage:(NSString *)message {
    
    UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alter addAction:action];
    [self presentViewController:alter animated:YES completion:^{ }];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    // 禁用返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

@end
